import { write, file, dir } from "opfs-tools";
interface OptionsInt {
  mimeType?: string;
}

function blobToBase64(blob: Blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

function isIosOrMac() {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === "MacIntel";
}

/**
 * 将 Blob 地址转换为 MP4 类型的 Blob 对象
 * @param {string} blobUrl - Blob 地址
 * @returns {Promise<Blob>} 转换后的 MP4 类型的 Blob 对象
 */
const blobUrlToMP4Blob = async (blobUrl: string) => {
  try {
    const response = await fetch(blobUrl);
    const arrayBuffer = await response.arrayBuffer();
    const mp4Blob = new Blob([arrayBuffer], { type: "video/mp4" });

    return mp4Blob;
  } catch (error) {
    throw new Error("Failed");
  }
};

/**
 * 利用web的 OPFS来缓存二进制文件，以减少流量浪费。
 * @param url
 * @returns
 */
export async function getOpfsUrl(url: string, { mimeType }: OptionsInt = {}) {
  console.log("isIosOrMac", isIosOrMac());
  if (isIosOrMac()) {
    return url;
  }

  try {
    const lurl = new URL(url);
    const DIRFIX = "/star";
    const isexists = await dir(DIRFIX).exists();
    if (!isexists) {
      await dir(DIRFIX).create();
    }
    const LOCA_PATH = DIRFIX + lurl.pathname;
    const isLocalPathExists = await file(LOCA_PATH).exists();
    if (!isLocalPathExists) {
      fetch(url).then(async (res) => {
        try {
          const blop = await res.blob();
          write(LOCA_PATH, await blop.arrayBuffer());
        } catch (error) {
          console.log(error);
        }
      });
      return url;
    }

    const buffer = await file(LOCA_PATH).arrayBuffer();
    const blob = new Blob([buffer], { type: mimeType });

    const localurl = URL.createObjectURL(blob);
    console.log("使用本地缓存文件：", localurl);

    return localurl;
  } catch (error) {
    console.log(error);
    return url;
  }
}
